package com.dsp.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.core.util.Constants;
import com.core.util.DspUtil;
import com.dsp.bean.Message;

public class DspController<T> {
	
	protected Logger logger = Logger.getLogger(DspUtil.Log4J);
	
	private Class<T> beanCls ;
	
	private HttpServletRequest request ;
	private HttpServletResponse response;
	
	protected int page ;
	protected int rp;
	
	public DspController(Class<T> cls){
		this.beanCls = cls;
	}
	/**
	 * 初始化
	 * @param request
	 * @param response
	 */
	protected void initHttp(HttpServletRequest request, HttpServletResponse response){
		this.request = request;
		this.response = response;
		this.page = Integer.valueOf(DspUtil.req(this.request.getParameter("page") , "1"));
		this.rp = Integer.valueOf(DspUtil.req(this.request.getParameter("rows"), String.valueOf(Constants.pageSize)));
	}
	
	/**
	 * 得到页面中的查询参数 
	 * @param dc
	 * @param column
	 * @param type
	 */
	protected void getPageParameters(DetachedCriteria dc , String[] column , String[] type) throws Exception{
		String tmpString = null , tmpValue = null;
		for(int index = 0 ; index < column.length ; index++){
			tmpString = column[index];
			tmpValue  = request.getParameter(Constants.QueryPrefix + tmpString);
			if(!DspUtil.isEmpty(tmpValue)){
				addDetachedCriteria(dc, tmpString, tmpValue, type[index]);
			}
		}
	}
	
	/**
	 * 
	 * @param dc 需要查询的对象
	 * @param columnName 被查询的名称
	 * @param obj 查询值
	 */
	protected void addDetachedCriteria(DetachedCriteria dc , String columnName , Object obj , String clsType){
			String val = String.valueOf(obj);
			String[] valArray = val.split("[,]");
			if (DspUtil.hasOnlyOne(valArray)){
				if (clsType.equalsIgnoreCase("Long")) {
					dc.add(Restrictions.eq(columnName, Long.valueOf(obj.toString())));
				} else if (clsType.equalsIgnoreCase("Integer")){
					dc.add(Restrictions.eq(columnName, Integer.valueOf(obj.toString())));
				} else {
					dc.add(Restrictions.like(columnName, val ,MatchMode.ANYWHERE));
				}
			} else {
				dc.add(Restrictions.in(columnName, valArray));
			}
	}
	
	/**
	 * 设置异常提示信息
	 * @param message
	 */
	protected void initMessage(Message message,String errorMsg){
		List<String> msg = new ArrayList<String>();
		msg.add(errorMsg);
		initMessage(message, msg);
	}
	
	/**
	 * 设置异常提示信息
	 * @param message
	 * @param msg
	 */
	protected void initMessage(Message message , List<String> msg){
		message.setSuccess(false);
		message.setMsg(msg);
	}
	
	public static void main(String[] args){
		Class<?> obj = Long.class;
		System.out.println(obj.getName());
		
	}

}
